import './assets/main.css';

import { createApp } from 'vue';
import App from './App.vue';
import { model, rotateDoor, door_isopen } from './blender.js';
import { publishDoor } from './App.vue';

createApp(App).mount('#app');

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import TWEEN from '@tweenjs/tween.js';

// 场景
const scene = new THREE.Scene();
scene.add(model); // 模型对象添加到场景中

// 辅助观察的坐标系
const axesHelper = new THREE.AxesHelper(100);
scene.add(axesHelper);

// 光源设置
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(400, 200, 300);
scene.add(directionalLight);
const ambient = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambient);

// 渲染器和相机
const width = window.innerWidth;
const height = window.innerHeight;
const camera = new THREE.PerspectiveCamera(8, width / height, 1, 500);
camera.position.set(0, 50, 90);
const x = 0, y = 0, z = 0;
camera.lookAt(x, y, z);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(x, y, z);
controls.update();

function render() {
    requestAnimationFrame(render);
    renderer.render(scene, camera);
    TWEEN.update();
}

window.onresize = function () {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
};

let selectedObject = null;

function onMouseClick(event) {
    const mouse = new THREE.Vector2();
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

    const raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(mouse, camera);

    const intersects = raycaster.intersectObjects(scene.children, true);

    if (intersects.length > 0) {
        const selected = intersects[0].object;
        console.log("Clicked object:", selected.name); // 确认对象名称
        if (selected.isMesh && selected.name === 'door') {
            console.log('selected');
            if (door_isopen) {
                publishDoor(0);
                rotateDoor(0);
            } else {
                publishDoor(1);
                rotateDoor(1);
            }
        }
    }
}
render();
window.addEventListener('click', onMouseClick, false);
